package com.ads.tpgrupo4.server.service.generarRemitosAClientes;

import java.util.List;

import com.ads.tpgrupo4.domain.cpr.remito.RemitoACliente;
import com.ads.tpgrupo4.server.config.Config;
import com.ads.tpgrupo4.server.fileserver.FileServer;
import com.ads.tpgrupo4.server.remote.PersistenceService;
import com.ads.tpgrupo4.server.service.generarCotizacionesPendientes.OutputFilesUrlUtils;
import com.ads.tpgrupo4.server.utils.UriUtils;
import com.ads.tpgrupo4.server.xml.XmlSource;
import com.ads.tpgrupo4.server.xml.mappers.RemitoAClienteXmlMapper;

public class GenerarRemitosAClientesService {

	private GeneradorDeRemitosAClientes generadorDeRemitosAClientes = GeneradorDeRemitosAClientes.getInstance();
	
	private PersistenceService persistenceService = PersistenceService.getInstance();
	
	private static GenerarRemitosAClientesService instance;
	
	public static GenerarRemitosAClientesService getInstance() {

		if (instance == null) {
			instance = new GenerarRemitosAClientesService();
		}
		
		return instance;
	}
	
	private GenerarRemitosAClientesService() {
	}
	
	public void generarRemitosAClientes() {
		
		try {
			
			final List<RemitoACliente> remitosAClientes = this.generadorDeRemitosAClientes.generarRemitosAClientes();
			
			this.persistenceService.saveRemitosAClientes(remitosAClientes);
			
			for (final RemitoACliente remitoACliente : remitosAClientes) {
				
				this.trySaveToFileSystem(remitoACliente);
			}
			
		} catch (final Exception e) {
			throw new GenerarRemitosAClientesServiceException();
		}
	}
	
	private void trySaveToFileSystem(final RemitoACliente remitoACliente) {
		
		try {		

			final String fileName = OutputFilesUrlUtils.getExpectedFileNameFor(remitoACliente);
			final String filePath = UriUtils.buildPath(Config.getInstance().getGeneratedFilesContainerDir(), fileName);
			
			final XmlSource asXml = RemitoAClienteXmlMapper.getInstance().map(remitoACliente);
			
			FileServer.createFile(asXml.toString(), filePath);
		
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}
	
}
